<?php

namespace App\Http\Controllers\Setting;

use App\Models\Role;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Acl;
use Illuminate\Support\Facades\DB;

class AclController extends Controller
{
    public function get(int $id)
    {
        $acls = Acl::where("role_id", $id)->get();

        $data = [];
        foreach ($acls as $acl) {
            $data[] = $acl->uri;
        }
        return response()->json($data);
    }

    public function auth(Request $request)
    {
        $this->validate($request, [
            'id' => 'required',
        ]);

        $id = (int)$request->get('id');
        $ids = $request->get('uris', []);

        $role = Role::find($id);
        if (!$role) {
            return redirect()->back()->withErrors("角色数据错误");
        }

        DB::transaction(function () use ($id, $ids) {

            Acl::where('role_id', $id)->delete();
            foreach ($ids as $uri) {
                $acl = new Acl();
                $acl->role_id = $id;
                $acl->uri = $uri;
                $acl->save();
            }
        });

        return redirect()->back()->withInput(["[{$role->name}]权限配置成功"]);
    }
}
